﻿package utils
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	/**
	 * 文件操作工具类
	 * @author jcg
	 */
	public class EasyFile
	{
		/**
		 * 保存文件
		 * data目前支持3种格式, String, byteArray,XML
		 */
		public static function saveFile(url:String, data:Object):void
		{
			var file:File = new File(url);
			var stream:FileStream = new FileStream(); 
			if(data is ByteArray)
			{
				stream.open(file, FileMode.WRITE);
				stream.writeBytes(data as ByteArray);
				stream.close();
			}
			else if(data is String)
			{
				stream.open(file, FileMode.WRITE);
				stream.writeUTFBytes(data as String);
				stream.close();
			}
			else if(data is XML)
			{
				stream.open(file, FileMode.WRITE);
				stream.writeUTFBytes(data.toString());
				stream.close();
			}
			else
			{
				stream.open(file, FileMode.WRITE);
				stream.writeObject(data);
				stream.close();
			}
		}
		
		/**
		 *	 以Json字符串的格式读取一个ddd文件
		 * @param url
		 * @return 
		 * 
		 */
		public static function loadDDDData(url:String):Object
		{
			var file:File = new File(url);
			if(!file.exists) return null;
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			var bt:ByteArray = new ByteArray();
			stream.readBytes(bt);
			stream.close();
			bt.uncompress();
			var obj:Object = bt.readObject();
			return obj;
		}
		
		/**
		 * 以字符串的格式读取一个文件
		 */
		public static function loadStringData(url:String):String
		{
			var file:File = new File(url);
			if(!file.exists) return "";
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			var str:String = stream.readUTFBytes(stream.bytesAvailable);
			stream.close();
			return str;
		}
		
		/**
		 * 以二进制的格式读取一个文件
		 */
		public static function loadByteArryData(url:String):ByteArray
		{
			var file:File = new File(url);
			if(!file.exists) return null;
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			var bt:ByteArray = new ByteArray();
			stream.readBytes(bt);
			stream.close();
			return bt;
		}
		
		/**
		 *	 以xml的格式读取一个文件
		 * @param url
		 * @return 
		 * 
		 */
		public static function loadXmlData(url:String):XML
		{
			var bt:ByteArray =loadByteArryData(url);
			if(bt==null)return null;
			var str:String = bt.readUTFBytes(bt.bytesAvailable);
			return XML(str);
		}
	}
}